# -*- coding: utf-8 -*-
"""
Created on Sat May  1 17:14:14 2021

@author: Apple
"""

import os
import sys
from PyQt5.QtWidgets import (QAbstractItemView,QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem,QHeaderView)
from main_window import Ui_MainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from 最小二乘法 import *


class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.actionopen.triggered.connect(self.openfile)
        self.ui.actionabout.triggered.connect(self.showversion)
        
        tableWidget = self.ui.tableWidget
        tableWidget.setRowCount(1)
        tableWidget.setColumnCount(2)
        
        for i in range(2):          
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(0,i,newItem)
        
        global A
        A = ['x','y']
        tableWidget.setHorizontalHeaderLabels(A)
        
    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版号为 V1.0 ')
        
    
    def newrow(self):
        
        tableWidget = self.ui.tableWidget
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        tableWidget.insertRow(numrow)
        for i in range(numcol):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(numrow,i,newItem)
    
    def delrow(self):

        tableWidget = self.ui.tableWidget
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        if numrow == 1:
            tableWidget.removeRow(0)
            tableWidget.insertRow(0)
            for i in range(numcol):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget.setItem(0,i,newItem)            
        else:
            tableWidget.removeRow(numrow-1)
            
    def cleartable(self):
        
        A = ['x','y']
        tableWidget = self.ui.tableWidget
        tableWidget.clear()
        tableWidget.setRowCount(1)
        tableWidget.setColumnCount(2)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget.setItem(0,1,newItem)
        
        tableWidget.setHorizontalHeaderLabels(A)
        tableWidget.setEditTriggers(QAbstractItemView.AllEditTriggers)
        
    def savedata(self):
        tableWidget = self.ui.tableWidget
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        path = os.getcwd() + '\\testdata.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.columns = ['x','y']
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')    
    
    def readfile(self):
        
        tableWidget = self.ui.tableWidget
                
        x = []
        y = []
        data = pd.read_csv('testdata.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        
        tableWidget.setRowCount(len(Data))
        tableWidget.setColumnCount(2)
        
        for i in range(len(Data)):
            x.append(Data[i][0])
            y.append(Data[i][1])
        
        for i in range(len(x)):
            newItem = QTableWidgetItem(f'{format(x[i],".3f")}')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(i,0,newItem)
        
        for i in range(len(y)):
            newItem = QTableWidgetItem(f'{format(y[i],".3f")}')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(i,1,newItem) 
    
    def transNtoC(self,methodname):
        methodCode = 0
        if methodname == '一阶多项式':
            methodCode = 2
        elif methodname == '二阶多项式':
            methodCode  = 3
        elif methodname =='三阶多项式':
            methodCode  = 4
   
        return methodCode

    def fitcurve(self):
        methodname = self.ui.comboBox.currentText()
        methodCode = self.transNtoC(methodname)
        X = [] #节点
        Y = [] # 节点对应的函数值
        a = methodCode  # 拟合函数个数
        
        X,Y = read_data()
        
        A = np.zeros((a,a)) # Ax=B
        for i in range(a):
            for j in range(a):
                A[i][j] = markA(i,j,X,len(X))
        
        B = np.zeros((a,1))
        for i in range(a):
            B[i][0] = markB(i,X,Y,len(X))
        
        x = np.linalg.solve(A,B) # 求解x
        y = functioncal(x,X)
            
        r = [] # 存储误差
        for i in range(len(Y)):
            r.append(Y[i]-y[i])
            
        SE = SEcal(r) # 平方误差
        e2 = math.sqrt(SE) # 2范数误差
        RMSE = math.sqrt(SE/len(r)) # 平均平方根误差
        
        print('平方误差为：',format(SE,".3f"))
        print('2范数误差为：',format(e2,".3f"))
        print('平均平方根误差为：',format(RMSE,".3f"))
    
    
        fig = plt.figure(figsize=(8,6),dpi=300) # 设置图片大小
        ax = fig.add_subplot(111)
        plt.rcParams['font.sans-serif']=['SimHei']
        
        plt.scatter(X,Y,s=np.pi * 1**2,c='#00CED1',label='原始数据') # 绘制散点图
        
        plt.plot(X,y,color='red',linestyle='-',linewidth=1,label='拟合曲线') # 绘制折线图
        
        plt.legend(loc='upper left') # 图例位置位于左上方
        plt.legend(loc='best')
        plt.xlabel('x') # 设置坐标标题
        plt.ylabel('y')
        
        plt.text(0.4,0.8,f'平方误差为：{format(SE,".3f")}'+'\n'+f'2范数误差为：{format(e2,".3f")}'+'\n'+f'平均平方根误差为：：{format(RMSE,".3f")}',transform=ax.transAxes)
        
        title = ''
        a_str = []
        b_str = ['']
        c_str = ['']
    
        for i in range(a):
            a_str.append(format(x[i][0],".3f"))
        
        for i in range(a-1):
            b_str.append(f'x^{i+1}')
            c_str.append('+')
        
        for i in range(a-1,-1,-1):
            title += a_str[i]+b_str[i]+c_str[i]
    
        plt.title('拟合函数:'+title)
        
        plt.savefig('test.jpg',dpi=300) # 保存图片
        
        pic = QPixmap('test.jpg')
        self.ui.picturelabel.setPixmap(pic)
        self.ui.picturelabel.setScaledContents(True)
        
        

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())